﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Web.Security;
using System.Collections.Generic;

namespace SoftwareDiscipline.SharePoint.UserManagement.ApplicationPages
{


    /// <summary>
    /// 
    /// </summary>
    public partial class NewUserPage : LayoutsPageBase
    {
        /// <summary>
        /// 
        /// </summary>
        private string roleName = String.Empty;

        private Dictionary<MembershipCreateStatus, string> CreateStatusMessages = new Dictionary<MembershipCreateStatus, string>()
        {
            { MembershipCreateStatus.DuplicateEmail, "A user with the same e-mail address already exists in the user database."},
            { MembershipCreateStatus.DuplicateProviderUserKey, "A user with the same key address already exists in the user database."},
            { MembershipCreateStatus.DuplicateUserName, "A user with the same user name already exists in the user database."},
            { MembershipCreateStatus.InvalidAnswer, "Invalid answer specified"},
            { MembershipCreateStatus.InvalidEmail, "Invalid e-mail address specified for the user"},
            { MembershipCreateStatus.InvalidPassword, "Invalid password specified. Please check the length and complexity of the password and try again."},
            { MembershipCreateStatus.InvalidProviderUserKey, "The key specified was invalid"},
            { MembershipCreateStatus.InvalidQuestion, "The key specified was invalid"},
            { MembershipCreateStatus.InvalidUserName, "The user name specified is invalid."},
            { MembershipCreateStatus.ProviderError, "There was an unknown error creating the user"},
            { MembershipCreateStatus.UserRejected, "The user was rejected for unknown reason."},
        };

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                SqlMembershipProvider provider = this.GetMembershipProvider();
                if (provider != null)
                {
                    string userName = this.textUserName.Text;
                    string emailAddress = this.textEmailAddress.Text;
                    string password = this.textPassword.Text;
                    MembershipCreateStatus status;

                    MembershipUser newUser = provider.CreateUser(userName, password,
                        emailAddress, null, null, true, Guid.NewGuid(), out status);
                    if (status != MembershipCreateStatus.Success)
                    {
                        throw new Exception(CreateStatusMessages[status]);
                    }

                    // check if we need to add this user to the role
                    if (!String.IsNullOrEmpty(RoleName))
                    {
                        SqlRoleProvider roleProvider = this.GetRoleProvider();
                        if (roleProvider != null)
                        {
                            if (roleProvider.RoleExists(this.RoleName))
                            {
                                roleProvider.AddUsersToRoles(new string[] { newUser.UserName }, new string[] { this.RoleName });
                            }
                        }
                    }

                    // close the window
                    this.CloseWindow();
                }
            }
            catch (Exception ex)
            {
                this.LabelErrorMessage.Text = "Error creating the new user: " + ex.Message;
            }
        }


        /// <summary>
        /// Closes the window.
        /// </summary>
        private void CloseWindow()
        {
            if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "__SW_UserManagement_NewUser_CloseWindow"))
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "__SW_UserManagement_NewUser_CloseWindow", "window.frameElement.commitPopup();", true);
            }
        }

        /// <summary>
        /// Gets the membership provider.
        /// </summary>
        /// <returns></returns>
        private SqlMembershipProvider GetMembershipProvider()
        {
            SPWebApplication webApp = SPContext.Current.Site.WebApplication;
            if (webApp != null)
            {
                // find the current zone
                SPUrlZone currentZone = SPContext.Current.Site.Zone;

                return webApp.GetSqlMembershipProvider(currentZone);
            }

            return null;
        }

        /// <summary>
        /// Gets the membership provider.
        /// </summary>
        /// <returns></returns>
        private SqlRoleProvider GetRoleProvider()
        {
            SPWebApplication webApp = SPContext.Current.Site.WebApplication;
            if (webApp != null)
            {
                // find the current zone
                SPUrlZone currentZone = SPContext.Current.Site.Zone;

                return webApp.GetSqlRoleProvider(currentZone);
            }

            return null;
        }

        /// <summary>
        /// Gets the name of the role.
        /// </summary>
        /// <value>The name of the role.</value>
        protected string RoleName
        {
            get
            {
                if (String.IsNullOrEmpty(this.roleName))
                {
                    roleName = this.Page.Request.QueryString["Role"];
                }

                return this.roleName;
            }
        }

    }
}
